package com.apestech.api.condition;

import com.apestech.formwork.condition.ConditionUtil;
import com.apestech.framework.db.SqlResultSet;
import com.apestech.framework.db.SqlSession;
import com.apestech.framework.db.callback.QueryCallBackHandler;
import com.apestech.framework.db.callback.ResultValueMapping;
import com.apestech.framework.dictionary.modul.Table;
import com.apestech.framework.json.JSON;
import com.apestech.framework.json.JSONArray;
import com.apestech.framework.json.JSONObject;
import com.apestech.framework.util.DBPub;
import com.apestech.framework.util.StringFuncUtil;
import com.apestech.framework.util.callback.SpiltStrCallback;
import com.apestech.framework.xml.ReadXmlNodeInter;
import com.apestech.framework.xml.condition.modul.Condition;
import com.apestech.framework.xml.condition.modul.Dimension;
import com.apestech.framework.xml.plugin.XmlPaste;
import com.apestech.framework.xml.pub.WriteXml;
import org.dom4j.Element;

import java.sql.SQLException;
import java.util.ArrayList;

public class ConditionErpToEsb extends StringFuncUtil {

    public class MapField{
        private String fields="";
        private String ismap="1";
        public String getFields() {
            return fields;
        }
        public void setFields(String fields) {
            this.fields = fields;
        }

        public String getIsmap() {
            return ismap;
        }

        public void setIsmap(String ismap) {
            this.ismap = ismap;
        }
    }

    private SqlSession ssession;
    private SqlSession dsession;
    private WriteXml xml;
    private JSONObject mapping;

    public ConditionErpToEsb(SqlSession ssession, SqlSession dsession) throws Exception {
        this.ssession=ssession;
        this.dsession=dsession;
        mapping=new JSONObject();
        ssession.getForResultSet().sql("SELECT * FROM HP_WDDZ WHERE 1=1 ", new QueryCallBackHandler(){
            @Override
            public void getData(SqlResultSet rs, JSONArray rslist) throws Exception {
                while(rs.next()){
                    JSONObject m=rs.toRowJson();
                    mapping.put(m.getString("F_ERP"),m);
                }
            }
        });
    }

    public void writeConditionDef() throws Exception {
        xml=new WriteXml();
        xml.createXml();
        Element root=xml.getRoot();
        String sql="SELECT A.TJCLID,A.TJCLMC,A.MRYXQ,A.JGLX FROM STR_TJCL A WHERE 1=1 ";
        ssession.getForResultSet().sql(sql, new JSONObject(), new QueryCallBackHandler() {
            @Override
            public void getData(SqlResultSet rs, JSONArray rslist) throws Exception {
                while(rs.next()){
                    Element econ=root.addElement("conditionDef");
                    String id=rs.getString("TJCLID");
                    econ.addAttribute("id", id);
                    econ.addAttribute("name", rs.getString("TJCLMC"));
                    econ.addAttribute("expiring", rs.getString("MRYXQ"));
                    econ.addAttribute("type", rs.getString("JGLX"));

                    Element edim=econ.addElement("dimensions");
                    String sql="<rule from=\"A.STR_TJCQSX\" /> SELECT A.TJCLID,A.XH,A.WDID,A.WDMC,A.CLMXB,A.CLZXB,A.GYSJGBJ,A.SL_MXB,A.SL_ZXB,A.ZWMC,A.ZXSXID,A.ZXSXMC,\n" +
                            "  (SELECT TO_CHAR(WM_CONCAT(B.ZDMC)) FROM STR_TJWDZD B WHERE A.WDID=B.WDID GROUP BY B.WDID) ZDMC\n" +
                            "FROM STR_TJCQSX A WHERE 1=1 @WHERE@ ORDER BY A.XH ";
                    JSONObject m=new JSONObject();
                    m.put("TJCLID", id);
                    ssession.getForResultSet().sql(sql, m, new QueryCallBackHandler() {
                        @Override
                        public void getData(SqlResultSet rsmx, JSONArray rslist) throws Exception {
                            while(rsmx.next()){
                                //<field fields="PRODUCT_ID,COMPANY_ID" master="COMPANY_ID"/>
                                String ZDMC=rsmx.getString("ZDMC");
                                String sys_table=rsmx.getString("CLZXB");
                                String fields="GSID,"+ZDMC;
                                MapField mapfield=new MapField();
                                execSplitStr(fields, ",", new SpiltStrCallback() {
                                    @Override
                                    public void exec(String id) throws Exception {
                                        String fields=mapfield.getFields();
                                        if(!"".equals(fields)){
                                            fields=fields+",";
                                        }
                                        String nid=((JSONObject)mapping.get(id)).getString("F_ESB");
                                        if(nid==null){
                                            mapfield.setIsmap("0");
                                            fields=fields+id;
                                        } else {
                                            fields=fields+nid;
                                        }
                                        mapfield.setFields(fields);
                                    }
                                });
                                if("1".equals(mapfield.getIsmap())){
                                    Element field=edim.addElement("field");
                                    field.addAttribute("fields", mapfield.getFields());
                                    field.addAttribute("ERP_TABLE", sys_table);
                                }
                                m.put("sys_table",sys_table);
                            }
                        }
                    });

                    String sys_table=m.getString("sys_table");
                    m.remove("sys_table");
                    Table table=ssession.getDictTable(sys_table);

                    Element econtrol=econ.addElement("control");
                    sql="<rule from=\"A.STR_TJCLMX;B.STR_TJLX\" /> SELECT A.TJCLID,A.TJLXID,A.TJLXMC,A.SFZD,A.XH,B.DYFS FROM STR_TJCLMX A, STR_TJLX B\n" +
                            "WHERE A.TJLXID=B.TJLXID AND 1=1 @WHERE@ ORDER BY A.XH";
                    ssession.getForResultSet().sql(sql, m, new QueryCallBackHandler() {
                        @Override
                        public void getData(SqlResultSet rsde, JSONArray rslist) throws Exception {
                            while(rsde.next()){
                                String field=rsde.getString("TJLXID");
                                int DYFS=rsde.getInt("DYFS");
                                Element efield=econtrol.addElement("field");
                                if(DYFS==0){  //金额
                                    efield.addAttribute("id","AMOUNT");
                                } else if(DYFS==1){  //比率
                                    efield.addAttribute("id","RATE");
                                } else {
                                    efield.addAttribute("type", table.getDbType(field));
                                    efield.addAttribute("notNull", table.getNotNull(field));
                                    efield.addAttribute("defaultValue", table.getColumnDef(field));
                                    if(table.getPkKey()!=null){
                                        String col=table.getPkKey().getPkColumn();
                                        if((","+col+",").indexOf(","+field+",")>=0){
                                            efield.addAttribute("isKey", "true");
                                        }
                                    }
                                }
                                efield.addAttribute("field",field);
                                efield.addAttribute("name", rsde.getString("TJLXMC"));
                            }
                        }
                    });
                }
            }
        });
        xml.writeXml("D:\\mywork\\new\\apes-server\\config\\erp.xml");
    }

    public void writeConditionStrategyDef() throws Exception {
        xml=new WriteXml();
        xml.createXml();
        Element root=xml.getRoot();
        String sql="SELECT A.DJGCID,A.DJGCMC,A.JGLX FROM STR_DJGC A WHERE 1=1 ";
        ssession.getForResultSet().sql(sql, new JSONObject(), new QueryCallBackHandler() {
            @Override
            public void getData(SqlResultSet rs, JSONArray rslist) throws Exception {
                while(rs.next()){
                    String id=rs.getString("DJGCID");
                    JSONObject m=new JSONObject();
                    m.put("DJGCID", id);
                    Element econ=root.addElement("conditionStrategyDef");
                    econ.addAttribute("id", id);
                    econ.addAttribute("name",rs.getString("DJGCMC"));
                    econ.addAttribute("default_0","0");
                    String sql="SELECT A.DJGCID,A.RCID,A.RCMC,A.DYFS FROM STR_DJGCRC A WHERE 1=1 ";
                    ssession.getForResultSet().sql(sql, m, new QueryCallBackHandler() {
                        @Override
                        public void getData(SqlResultSet rszd, JSONArray rslist) throws Exception {
                            while(rszd.next()){
                                String RCID=rszd.getString("RCID");
                                String RCMC=rszd.getString("RCMC");
                                Element eif=econ.addElement("if");
                                eif.addAttribute("name", RCMC);
                                eif.addElement("exp").addCDATA("return "+RCID+"==null");
                                Element ethen=eif.addElement("then");
                                ethen.addAttribute("break","1");
                                ethen.addAttribute("msg","["+RCMC+"]不允许为空，请检查入参！");
                            }

                        }
                    });

                    if("CG03".equals(id)){
                        System.out.println("");
                    }
                    sql="<rule from=\"A.STR_DJGCMX\" />SELECT A.DJGCID,A.TJCLID,A.TJCLMC,A.TJLXID,A.TJLXMC,A.EXPRESS,A.FHBJ,A.ERRMSG,A.FHZ,\n" +
                            "   A.TJKQSBJ,A.DWZDHSBJ,A.QZBJ\n" +
                            "FROM STR_DJGCMX A WHERE 1=1 @WHERE@ ORDER BY A.XH ";
                    ssession.getForResultSet().sql(sql, m, new QueryCallBackHandler() {
                        @Override
                        public void getData(SqlResultSet rsmx, JSONArray rslist) throws Exception {
                            //<condition id="TC01" name="取平台销售提成规则" break="1" outputfields="T001,T002,T021,T011,T022,T012,T023,T013,T024,T014,T401"  />  --msg="取平台销售提成规则出错"
                            JSONObject param=null;
                            String pTJCLID=null;
                            String feild="";
                            while(rsmx.next()){
                                JSONObject json=rsmx.toRowJson();
                                String TJCLID=json.getString("TJCLID");
                                boolean flag=(TJCLID!=null && pTJCLID==null);
                                if(!flag) flag=(TJCLID==null && pTJCLID!=null);
                                if(!flag) flag=(TJCLID!=null && pTJCLID!=null && !TJCLID.equals(pTJCLID));
                                if(flag){
                                    if(param!=null){
                                        Element econdition=econ.addElement("condition");
                                        econdition.addAttribute("id", pTJCLID);
                                        econdition.addAttribute("name", param.getString("TJCLMC"));
                                        econdition.addAttribute("break", param.getString("FHBJ"));
                                        econdition.addAttribute("outputfields", feild);
                                        feild="";
                                    }
                                    if(TJCLID==null){
                                        param=null;
                                        pTJCLID=null;
                                        feild="";
                                    } else {
                                        param=new JSONObject();
                                        param.putAll(json);
                                        pTJCLID=param.getString("TJCLID");
                                        feild=param.getString("TJLXID");
                                    }
                                } else {
                                    if(json.get("TJCLID")!=null){
                                        feild=feild+","+json.getString("TJLXID");
                                    }
                                }
                                if(TJCLID==null){
                                    Element econdition=econ.addElement(json.getString("TJLXID"));
                                    econdition.addAttribute("id", TJCLID);
                                    econdition.addAttribute("name", json.getString("TJLXMC"));
                                    econdition.addAttribute("break", json.getString("FHBJ"));
                                    econdition.addCDATA(json.getString("EXPRESS"));
                                }
                            }
                            if(!"".equals(feild) && param!=null){
                                Element econdition=econ.addElement("condition");
                                econdition.addAttribute("id", pTJCLID);
                                econdition.addAttribute("name", param.getString("TJCLMC"));
                                econdition.addAttribute("break", param.getString("FHBJ"));
                                econdition.addAttribute("outputfields", feild);
                            }
                        }
                    });
                }
            }
        });
        xml.writeXml("D:\\mywork\\new\\apes-server\\config\\erp_c.xml");
    }

    public void exportData() throws Exception {
        ArrayList<String> flist=ConditionUtil.getFileTypeIdList(dsession, "D:\\mywork\\new\\apes-server\\config\\query\\condition\\esb\\erp_0419.xml", "conditionDef");
        ArrayList<String> fklist=new ArrayList<String>();
        JSONObject error=new JSONObject();
        int len=flist.size();
        for(int i=0; i<len; i++){
            Condition condition= ConditionUtil.getCondition(flist.get(i), dsession);
            ArrayList<Dimension> dim=condition.getDimension();
            int dlen=dim.size();
            if(dlen>0){
                condition.getTables();
                for(int d=0; d<dlen; d++){
                    Dimension dm=dim.get(d);
                    if(dm.isIsmap()){
                        String tabName=condition.getTableKey().getTabName(dm.getId())+"_EXEC";
                        String fromTab=dm.getFromTab();
                        insertTable(condition, fromTab, tabName, fklist, error);
                    }
                }
            }
        }
        System.out.println(JSON.toJSONString(error));
        System.out.println(JSON.toJSONString(fklist));
    }

    public void exportData(String cid, String mid) throws Exception {
        Condition condition= ConditionUtil.getCondition(cid, dsession);
        Dimension dm=condition.getDimensionById(mid);
        String tabName=condition.getTableKey().getTabName(mid)+"_EXEC";
        String fromTab=dm.getFromTab();
        insertTable(condition, fromTab, tabName, null, null);
    }

    public void exportData(String cid) throws Exception {
        Condition condition= ConditionUtil.getCondition(cid, dsession);
        ArrayList<Dimension> dlist=condition.getDimension();
        int dlen=dlist.size();
        for(int d=0; d<dlen; d++){
            Dimension dm=dlist.get(d);
            String tabName=condition.getTableKey().getTabName(dm.getId())+"_EXEC";
            String fromTab=dm.getFromTab();
            insertTable(condition, fromTab, tabName, null, null);
        }
    }

    public void exportDataFromTab(String cid, String tableid) throws Exception {
        Condition condition= ConditionUtil.getCondition(cid, dsession);
        ArrayList<Dimension> dlist=condition.getDimension();
        int dlen=dlist.size();
        for(int d=0; d<dlen; d++){
            Dimension dm=dlist.get(d);
            if(tableid.equals(dm.getFromTab())){
                String tabName=condition.getTableKey().getTabName(dm.getId())+"_EXEC";
                String fromTab=dm.getFromTab();
                insertTable(condition, fromTab, tabName, null, null);
                break;
            }
        }
    }

    private void insertTable(Condition condition, String fromTab, String tabName, ArrayList<String> fklist, JSONObject error) throws Exception {
        Table stab=ssession.getDictTable(fromTab);
        Table dtab=dsession.getDictTable(tabName);
        String scol=stab.getColumn();
        String dcol=dtab.getColumn();
        final String[] sfield = {""};
        execSplitStr(scol, ",", new SpiltStrCallback(){
            @Override
            public void exec(String id) throws Exception {
                String nid=null;
                if(condition.getMapping()!=null){
                    nid=condition.getMapping().getString(id);
                }
                if(nid==null){
                    if(mapping.get(id)!=null){
                        nid=((JSONObject)mapping.get(id)).getString("F_ESB");
                    } else {
                        if("TZDH".equals(id)) nid="ID";
                        else if("YXQQ".equals(id)) nid="START_DATE";
                        else if("YXQZ".equals(id)) nid="END_DATE";
                        else nid="";
                        //else if("YXJ".equals(id)) nid="PRIORITY";
                    }
                }

                if((","+dcol+",").indexOf(","+nid+",")>=0 || (","+dcol+",").indexOf(","+id+",")>=0){
                    sfield[0] = sfield[0] +", A."+id+" "+nid;
                }
            }
        });
        System.out.println("from:"+fromTab+" to:"+tabName);
        if("TJCL_40009_ZX".equals(fromTab)){
            sfield[0]=sfield[0]+", A.GSID ACCESS_PROVIDER_ID";
        }
        String sql="SELECT 'exec' STATE, SYSDATE CREATE_DATE, SYSDATE UPDATE_DATE, SYSDATE LAST_UPDATED_STAMP, 0 PRIORITY"+sfield[0]+" FROM "+fromTab+" A WHERE 1=1 ";
//        dsession.getForDDL().truncateTable(tabName);
        dsession.getForDDL().disableTableFk(tabName);
        try{
            dsession.getForUpdate().insertTable_M("prod.erp", tabName, sql, new JSONObject(), new ResultValueMapping(){
                @Override
                public Object getField(String field, Object value, SqlResultSet rs) throws Exception {
                    if("TJCL_40009_ZX".equals(fromTab) && "ACCESS_PROVIDER_ID".equals(field)){
                        JSONObject m=new JSONObject();
                        m.put("ACCESS_PROVIDER_ID", rs.getObject("ACCESS_PROVIDER_ID"));
                        m.put("autoCompletion","0");
                        m.put("printSql","false");
                        String sql="SELECT A.ACCESS_PROVIDER_ID FROM MAS_PARTY_ROLE A WHERE A.ACCESS_PROVIDER_ID IS NOT NULL AND ID = #{ACCESS_PROVIDER_ID}";
                        final Object[] v = {null};
                        dsession.getForResultSet().sql(sql, m, new QueryCallBackHandler() {
                            @Override
                            public void getData(SqlResultSet rs, JSONArray rslist) throws Exception {
                                if(rs.next()){
                                    v[0] =rs.getObject("ACCESS_PROVIDER_ID");
                                }
                            }
                        });
                        return v[0];
                    }
                    return value;
                }
            });
        } catch (Exception e){
            if(error!=null){
                JSONObject m=new JSONObject();
                m.put("sql", sql);
                m.put("msg", e.toString());
                error.put("tabName", m);
            } else {
                throw e;
            }
        }

        try{
            dsession.getForDDL().enableTableFk(tabName);
        } catch (Exception e){
            if(fklist!=null){
                fklist.add(tabName);
            } else {
                System.out.println(tabName);
            }
        }
    }

    public void addSumId() throws Exception {
        JSONArray list=ConditionUtil.getCondition(dsession);
        int len=list.size();
        for(int i=0; i<len; i++){
            JSONObject m=list.get(i);
            String id=m.getString("ID");
            Condition con=ConditionUtil.getCondition(id, dsession);
            ArrayList<Dimension> dlist=con.getDimension();
            int dlen=dlist.size();
            for(int d=0; d<dlen; d++){
                Dimension dim=dlist.get(d);
                String tabName=con.getTableKey().getTabName(dim.getId())+"_EXEC";
                String sql="SELECT DISTINCT ID FROM "+tabName+" WHERE 1=1 ";
                dsession.getForResultSet().sql(sql, new QueryCallBackHandler() {
                    @Override
                    public void getData(SqlResultSet rs, JSONArray rslist) throws Exception {
                        while(rs.next()){
                            JSONObject m=new JSONObject();
                            m.put("ID", DBPub.getIdKeyStr(dsession, "EXE_CONDITION_SUM"));
                            m.put("CONDITION_ID", con.getId());
                            m.put("DIMENSION_ID", dim.getId());
                            m.put("B_ID", rs.getString("ID"));
                            m.put("CREATE_DATE", "SYSDATE");
                            m.put("LAST_UPDATED_STAMP", "SYSDATE");
                            dsession.getForUpdate().insertTable("EXE_CONDITION_SUM", m);
                        }
                    }
                });
            }
        }
    }

}
